const path = require('path');
const fs = require("fs");
const multer = require('multer')
const mkdirp = require('mkdirp')
const moment = require('moment');

let tools = {
    multer(u) {
        //上传文件
        const storage = multer.diskStorage({
            destination: async(req, file, cb) => {
                let day = new moment().format('YYYY-MM-DD')
                    //获取用户

                let dir = path.join("public/avatar", day)
                    //根据用户名创建目录
                await mkdirp(dir)
                cb(null, dir) //配置上传目录
            },
            filename: (req, file, cb) => {
                let extname = path.extname(file.originalname)
                    //配置图片名称
                cb(null, file.fieldname + '-' + Date.now() + extname)
            }
        })
        const upload = multer({ storage: storage })
        return upload
    },

    //获取头像删除
    delfolder(pth) {
        let docpath = path.parse(pth) //格式化数据库路径

        let dbpath = "public" + docpath.dir; // 到日期文件夹
        let curPath = dbpath + "/" + docpath.base; //全部路径
        fs.readdir(dbpath, (err, files) => {

                if (err) { throw err }

                if (pth != "/avatar/default.png") {
                    //判断文件是否存在
                    if (fs.existsSync(curPath)) {
                        fs.stat(docpath.base, async(st) => {
                            await fs.unlink(curPath, (errs) => {
                                if (errs) {
                                    throw errs
                                };
                            });

                        });
                        // console.log(111, docpath.dir, files)
                        // if (files.length == 1) {
                        //     //删除空目录
                        //     fs.rmdir(dbpath, (err) => {
                        //         if (err) {
                        //             throw err;
                        //         }
                        //     });
                        // }

                    }


                }
            }) //获取文件夹end

    },

}

module.exports = tools